package com.hanxiaozhang.io.sockethttp;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈请求实体〉
 *
 * @author hanxinghua
 * @create 2023/6/25
 * @since 1.0.0
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class RequestEntity {

    /**
     * 请求行
     */
    private String requestLine;

    /**
     * 请求方法
     */
    private String method;

    /**
     * Url
     */
    private String url;

    /**
     * 版本协议
     */
    private String requestAndVersion;


    /**
     * header
     */
    private Map<String, String> headers;

    /**
     * 报文内容
     */
    private String body;


    /**
     * 字节数组转换request实体
     *
     * @param bytes
     * @return
     */
    public void byteToRequest(byte[] bytes) {
        // \r\n连续出现两次的情况认为首部结束，剩下是主体部分
        int flag = 0;
        // 是否为body内容
        boolean isBody = false;
        char temp;
        StringBuffer headerSb = new StringBuffer(),
                bodySb = new StringBuffer();
        Map<String, String> headers = new HashMap<>(16);

        // 解析请求报文头和请求body
        for (int i = 0; i < bytes.length; i++) {
            if (isBody) {
                bodySb.append((char) bytes[i]);
            } else {
                temp = (char) bytes[i];
                if (temp == '\r' || temp == '\n') {
                    flag++;
                } else {
                    flag = 0;
                }
                if (flag == 4) {
                    isBody = true;
                }
                headerSb.append(temp);
            }
        }

        // 解析请求行
        String[] lines = headerSb.toString().split("\r\n");
        String requestLine = lines[0];
        String[] requestLines = requestLine.split("\\s");
        this.setRequestLine(requestLine)
                .setMethod(requestLines[0])
                .setUrl(requestLines[1])
                .setRequestAndVersion(requestLines[2]);

        // 解析请求header
        for (int i = 1; i < lines.length; i++) {
            if (lines[i] != "") {
                String[] header = lines[i].split(": ");
                headers.put(header[0], header[1]);
            }
        }

        this.setHeaders(headers)
                .setBody(bodySb.toString());
    }

}
